package com.glory.wxmemsicpda.activity

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.glory.wxmemsicpda.BR
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.adapter.RejectCodeAdapter
import com.glory.wxmemsicpda.adapter.UpdateMaterialQTYAdapter
import com.glory.wxmemsicpda.adapter.WorkEndFailOutAdapter
import com.glory.wxmemsicpda.base.App
import com.glory.wxmemsicpda.base.BaseDialogActivity
import com.glory.wxmemsicpda.bean.EqpInfoBean
import com.glory.wxmemsicpda.bean.EqpListBean
import com.glory.wxmemsicpda.bean.MaterialsListBean
import com.glory.wxmemsicpda.bean.net.BaseResponseBean
import com.glory.wxmemsicpda.databinding.ActivityWorkEndPackageBinding
import com.glory.wxmemsicpda.utils.NetUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import kotlinx.android.synthetic.main.activity_work_begin.llMain
import kotlinx.android.synthetic.main.activity_work_end_package.*
import kotlinx.android.synthetic.main.dialog_reject_code.view.*

class WorkEndPackageActivity : BaseDialogActivity(), View.OnClickListener {

    private var mWorkEndEntity: EqpInfoBean? = null
    private var viewDataBinding: ActivityWorkEndPackageBinding? = null
    private var mAdapter: WorkEndFailOutAdapter? = null

    private var mRejectCodeDialog: FreeUI_GeneralFragmentDialog? = null
    private var defectCodeList: MutableList<EqpListBean?>? = null//不良代码列表(集合不变)
    private var defectCodeSecondList: MutableList<EqpListBean?>? = null//实际出现的不良代码

    private var rejectTotalQty: Int? = 0//总不良品数

    private var mDataList: MutableList<MaterialsListBean.MaterialsBean?>? = mutableListOf()
    private var updateMaterialQTYAdapter: UpdateMaterialQTYAdapter = UpdateMaterialQTYAdapter(
        mDataList
    )


    override fun getLayoutResId(): Int {
        return R.layout.activity_work_end_package
    }

    override fun initView() {
        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_end_package)
        setTitle("批次结束作业(封装)")
        mWorkEndEntity = intent.getSerializableExtra("Entity") as EqpInfoBean?
        etGoodQuantity.setText(mWorkEndEntity?.totaL_QUANTITY)
        defectCodeList = mWorkEndEntity?.defecT_CODE_LIST //该集合用于显示所有不良品代码，获取后不可再做更改。
        mDataList =
            mWorkEndEntity?.mtM_MAT_LIST as MutableList<MaterialsListBean.MaterialsBean?>? //获取物料批次信息


        rvMaterialsList.layoutManager = LinearLayoutManager(this)
        rvMaterialsList.adapter = updateMaterialQTYAdapter
        updateMaterialQTYAdapter.setNewData(mDataList)

        rvFailOutList.layoutManager = LinearLayoutManager(this)
        rvFailOutList.itemAnimator = DefaultItemAnimator()
        rvFailOutList.addItemDecoration(DividerItemDecoration(this, 1))

        flBadCode.setOnClickListener(this)
        tvAddBadCode.setOnClickListener(this)
        tvRemoveBadCode.setOnClickListener(this)
        cbCheckAllBadCode.setOnClickListener(this)//全选

        freeUI_titleView.setRightListener("结束作业") {
            if (etGoodQuantity.text.toString().isEmpty() || etGoodQuantity.text.toString().toInt() < 0){
                showToast("合格数不能小于0，请重新填写报废信息",false)
                return@setRightListener
            }

            val map = JsonObject()
            map.addProperty("EQP_ID", mWorkEndEntity?.eqP_ID)
            map.addProperty("LOT_ID", mWorkEndEntity?.loT_ID)
            map.addProperty("INPUT_TYPE", mWorkEndEntity?.inpuT_TYPE)
            map.addProperty("START_TIME", mWorkEndEntity?.starT_TIME)
            map.addProperty("END_TIME", mWorkEndEntity?.enD_TIME)
            map.addProperty("TOTAL_QUANTITY", mWorkEndEntity?.totaL_QUANTITY)
            map.addProperty("TOTAL_GOOD_QUANTITY", mWorkEndEntity?.totaL_GOOD_QUANTITY)
            map.addProperty("TOTAL_FAIL_QUANTITY", mWorkEndEntity?.totaL_FAIL_QUANTITY)
            map.addProperty("TESTER_PASS_QUANTITY", mWorkEndEntity?.testeR_PASS_QUANTITY)
            map.addProperty("TESTER_FAIL_QUANTITY", mWorkEndEntity?.testeR_FAIL_QUANTITY)
            map.add(
                "BIN_LIST",
                JsonParser().parse(Gson().toJson(mWorkEndEntity?.biN_LIST)).asJsonArray
            )
            map.add(
                "DEFECT_CODE_LIST",
                JsonParser().parse(Gson().toJson(defectCodeList?.filter { it!!.rejectS_QUANTITY.isNotEmpty() })).asJsonArray
            )
            map.add(
                "MTM_MAT_LIST",
                JsonParser().parse(Gson().toJson(updateMaterialQTYAdapter.data)).asJsonArray
            )
            NetUtils.requestPosNet(this,
                "PDALotEnd", "PDALotEnd",
                map,
                object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<EqpInfoBean?>?>(
                    this
                ) {
                    override fun onSuccess(response: Response<BaseResponseBean<EqpInfoBean?>?>) {
                        super.onSuccess(response)
                        if (response.body()!!.isSuccess(false, supportFragmentManager)) {
//                                    showToast("出站成功", true)
                            showMessageDialog(
                                response.body()!!.response.header.resultmessage,
                                supportFragmentManager
                            )
//                                    finish()
                        }
                    }

                    override fun onError(response: Response<BaseResponseBean<EqpInfoBean?>?>) {
                        super.onError(response)
                        loadError(response.exception, "PDALotEnd")
                    }
                })
        }
    }

    override fun initData() {
        viewDataBinding?.setVariable(BR.eqpInfoBean, mWorkEndEntity)
        defectCodeSecondList = ArrayList()

        mAdapter = WorkEndFailOutAdapter(defectCodeList) {
            val sumBy = defectCodeList?.sumBy { it!!.rejectS_QUANTITY.toIntOrNull() ?: 0 }
            mWorkEndEntity?.totaL_FAIL_QUANTITY = sumBy.toString()
            mWorkEndEntity?.totaL_GOOD_QUANTITY = (mWorkEndEntity!!.totaL_QUANTITY.toIntOrNull()!! - sumBy!!).toString()
            etGoodQuantity.setText(mWorkEndEntity?.totaL_GOOD_QUANTITY)
            viewDataBinding?.setVariable(BR.eqpInfoBean, mWorkEndEntity)
        }
        mAdapter?.isAnimationFirstOnly = false
        rvFailOutList.adapter = mAdapter
    }

    override fun getBaseEntity(): FreeUI_AddViewEntity {
        return FreeUI_AddViewEntity("header", llMain)
    }

    //显示不良代码
    private fun showRejectCode() {
        if (defectCodeList != null) {
            if (defectCodeList!!.size > 0) {
                showRejectCodeDialog(defectCodeList!!)
                return
            } else {
                showToast("该设备无不良代码！", true)
            }
        }
    }

    //不良代码弹出框
    @SuppressLint("InflateParams")
    private fun showRejectCodeDialog(rejectCodes: MutableList<EqpListBean?>) {
        mRejectCodeDialog = FreeUI_GeneralFragmentDialog()
        val view: View = LayoutInflater.from(this).inflate(R.layout.dialog_reject_code, null)
        view.btn_cancel.setOnClickListener { mRejectCodeDialog!!.dismiss() }
        mRejectCodeDialog!!.setLayout(view)
        //        mRejectCodeDialog.getDialog().setCanceledOnTouchOutside(false);
        mRejectCodeDialog!!.show(supportFragmentManager, "rejectCodeSelect")
        mRejectCodeDialog!!.setCallBack { mRejectCodeDialog = null }//弹出框退出后赋空
        val rejectCodeAdapter = RejectCodeAdapter(rejectCodes)
        view.lv_reject_code.layoutManager = LinearLayoutManager(this)
        view.lv_reject_code.adapter = rejectCodeAdapter

        rejectCodeAdapter.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
            tvBadCode.text = rejectCodes[position]?.rejectS_CODE
            mRejectCodeDialog!!.dismiss()
        })
    }

    //添加不良品代码
    private fun addRejectCode() {
        val sRejectCode = tvBadCode.text.toString()
        val sRejectQty = etBadNum.text.toString()
        var isAdded = false;//判断该不良代码是否已经添加过

        //判断是否选择了不良代码
        if (!TextUtils.isEmpty(sRejectCode)) {

            //判断是否输入了不良数量
            if (!TextUtils.isEmpty(sRejectQty)) {

                //判断是否有已添加的不良代码
                if (defectCodeSecondList?.isNotEmpty() == true) {

                    for (it in defectCodeSecondList!!) {

                        //判断该不良代码是否已经添加过
                        if (it?.rejectS_CODE.equals(sRejectCode)) {

                            var num = it?.rejectS_QUANTITY?.toInt()

                            //更新不良数量
                            num = num?.plus(sRejectQty.toInt())
                            it?.rejectS_QUANTITY = num.toString()

                            isAdded = true;
                        }
                    }
                    //如果该不良代码没有添加过，则添加
                    if (!isAdded) {
                        val eqpListBean = EqpListBean()
                        eqpListBean.rejectS_CODE = sRejectCode
                        eqpListBean.rejectS_QUANTITY = sRejectQty

                        defectCodeSecondList?.add(eqpListBean)
                    }
                } else {

                    val eqpListBean = EqpListBean()
                    eqpListBean.rejectS_CODE = sRejectCode
                    eqpListBean.rejectS_QUANTITY = sRejectQty

                    defectCodeSecondList?.add(eqpListBean)

                }

                mAdapter!!.setData(defectCodeSecondList)

                //更新总不良品数
                rejectTotalQty = rejectTotalQty?.plus(sRejectQty.toInt())
                tvFailOutQty.text = rejectTotalQty.toString()

                showToast("添加成功", true)

            } else {
                showToast("请输入不良数量！", false);
            }
        } else {
            showToast("请选择不良代码！", false)
        }
    }

    //删除不良品代码
    private fun deleteRejectCode() {
        //获取待删除数据
        var deleteData: ArrayList<EqpListBean?> = arrayListOf()
        deleteData.addAll(mAdapter!!.list)

        if (deleteData.isNotEmpty()) {
            //删除已选择的不良代码
            defectCodeSecondList?.removeAll(deleteData)
            mAdapter?.setData(defectCodeSecondList)

            mAdapter!!.list.clear()//清空已删除的不良代码

            //更新总不良数
            for (it in deleteData) {
                val num = it!!.rejectS_QUANTITY.toInt()
                rejectTotalQty = rejectTotalQty?.minus(num)
            }
            tvFailOutQty.text = (if (rejectTotalQty!! < 0) 0 else rejectTotalQty).toString()

            showToast("移除成功", true)

        } else {
            showToast("请选择要删除的数据！", false)
        }

        cbCheckAllBadCode.isChecked = false//取消全选状态

    }

    //消息提示框
    private fun showMessageDialog(message: String, fragmentManager: FragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
            App.app, "确定", message
        ) {
            finish()
        }.show(fragmentManager, "DIALOG")
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.flBadCode -> {
                showRejectCode()//选择不良代码
            }

            R.id.tvAddBadCode -> {
                addRejectCode()//添加
            }

            R.id.tvRemoveBadCode -> {
                deleteRejectCode()//删除

            }

            R.id.cbCheckAllBadCode -> {
                mAdapter!!.setAllChecked(cbCheckAllBadCode.isChecked)
            }
        }
    }
}